/*
 * Copyright (c) Jack魏 2024 - 2024, All Rights Reserved.
 */

package cn.jackwei.yiyi.service.sys;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.jackwei.yiyi.mapper.SysLoginMapper;
import cn.jackwei.yiyi.mapper.SysUserMapper;
import cn.jackwei.yiyi.pojo.bean.SysLogin;
import cn.jackwei.yiyi.pojo.bean.SysUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Jack魏
 * @since 2024-07-25
 */
@Service
public class SysLoginService extends ServiceImpl<SysLoginMapper, SysLogin> {
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 根据token获取用户信息
     *
     * @param token 登陆token
     * @return 用户信息
     */
    public SysUser getUserByToken(String token) {
        if (StrUtil.isEmpty(token)) {
            return null;
        }
        QueryWrapper<SysLogin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysLogin::getToken, token).gt(SysLogin::getStatus, 0).orderByDesc(SysLogin::getId).last("limit 1");
        SysLogin sysLogin = baseMapper.selectOne(queryWrapper);
        if (sysLogin == null) {
            return null;
        }
        // 过期了
        if (LocalDateTimeUtil.between(LocalDateTime.now(), sysLogin.getExpireTime(),
                ChronoUnit.SECONDS) < 0) {
            sysLogin.setStatus(-2);
            baseMapper.updateById(sysLogin);
            return null;
        }
        return sysUserMapper.selectById(sysLogin.getUserId());
    }

    /**
     * 用户退出系统
     */
    public void logout() {
        UpdateWrapper<SysLogin> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(SysLogin::getStatus, -1).eq(SysLogin::getToken,
                StpUtil.getTokenValue());
        baseMapper.update(updateWrapper);
        StpUtil.logout();
    }
}
